﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WJP.ManagedProperty
{
    /// <summary>
    /// 托管属性只读列表
    /// </summary>
    public class ManagedPropertyList : ICollection<IManagedProperty>
    {
        private IDictionary<string, IManagedProperty> Dic { get; set; }

        internal ManagedPropertyList()
        {
            Dic = new Dictionary<string, IManagedProperty>(10);
        }

        /// <summary>
        /// 添加托管属性
        /// </summary>
        /// <param name="properties"></param>
        internal void AddRange(IEnumerable<IManagedProperty> properties)
        {
            foreach (IManagedProperty property in properties)
                Dic[property.Name] = property;
        }

        /// <summary>
        /// 通过属性名称查找托管属性
        /// </summary>
        /// <param name="propertyName">托管属性名称</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public IManagedProperty Find(string propertyName, bool ignoreCase = false)
        {
            Check.NotNullOrWhiteSpace(propertyName, nameof(propertyName));

            if (ignoreCase)
            {
                foreach (var key in Dic.Keys)
                {
                    if (key.EqualsIgnoreCase(propertyName))
                        return Dic[key];
                }
            }
            else
            {
                if (Dic.TryGetValue(propertyName, out IManagedProperty managedProperty))
                    return managedProperty;
            }
            return null;
        }

        public IList<IManagedProperty> GetAll()
        {
            return Dic.Values.ToList();
        }

        public int Count => Dic.Count;

        public bool IsReadOnly => true;

        public void Add(IManagedProperty item)
        {
            Dic[item.Name] = item;
        }

        public void Clear()
        {
            throw new NotImplementedException();
        }

        public bool Contains(IManagedProperty item)
        {
            return Dic.Values.Contains(item);
        }

        public void CopyTo(IManagedProperty[] array, int arrayIndex)
        {
            Dic.Values.CopyTo(array, arrayIndex);
        }

        public IEnumerator<IManagedProperty> GetEnumerator()
        {
            return Dic.Values.GetEnumerator();
        }

        public bool Remove(IManagedProperty item)
        {
            throw new NotImplementedException();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
